<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>PyMOTW: tempfile &mdash; PyMOTW Document v1.6 documentation</title>
    <link rel="stylesheet" href="../_static/mytest.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.6',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    
    <!-- comment utility -->
    <link rel="stylesheet" href="../_static/comment.css" type="text/css" />
    <script type="text/javascript" src="../_static/md5.js"></script>
    <script type="text/javascript" src="../_static/comment.js"></script>
    <!-- end -->
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="PyMOTW Document v1.6 documentation" href="../index.html" />
    <link rel="next" title="PyMOTW: sched" href="sched.html" />
    <link rel="prev" title="PyMOTW: asyncore" href="asyncore.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="sched.html" title="PyMOTW: sched"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="asyncore.html" title="PyMOTW: asyncore"
             accesskey="P">previous</a> |</li>
        <li><a href="../index.html">PyMOTW Document v1.6 documentation</a> &raquo;</li> 
      </ul>
    </div> 
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">PyMOTW: tempfile</a><ul>
<li><a class="reference external" href="#id1">描述</a></li>
<li><a class="reference external" href="#id2">临时文件</a></li>
<li><a class="reference external" href="#id3">命名临时文件</a></li>
<li><a class="reference external" href="#mkdtemp">mkdtemp</a></li>
<li><a class="reference external" href="#id4">预测文件名</a></li>
<li><a class="reference external" href="#id5">临时文件的位置</a></li>
<li><a class="reference external" href="#id6">参考</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="asyncore.html"
                                  title="previous chapter">PyMOTW: asyncore</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="sched.html"
                                  title="next chapter">PyMOTW: sched</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/documents/tempfile.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div> 

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="pymotw-tempfile">
<h1>PyMOTW: tempfile<a class="headerlink" href="#pymotw-tempfile" title="Permalink to this headline">¶</a></h1>
<p>使用tempfile模块可以安全的生成临时文件和目录.</p>
<ul class="simple">
<li>模块: tempfile</li>
<li>目的: 创建临时的文件系统资源.</li>
<li>Python 版本: 1.4 + (主安全修订版本2.3)</li>
</ul>
<div class="section" id="id1">
<h2>描述<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<p>许多程序需要将产生的中间数据保存在文件中. 安全地创建一些具有唯一名字的文件,  使得想要中断应用的人无法猜测到这些文件的名字，这是具有挑战性的.  tempfile模块提供一些用于安全处理文件系统资源的函数. TemporaryFile()打开并返回一个未命名文件. NamedTemporaryFile() 打开并返回一个已命名文件, mktemp()可以创建一个临时目录并返回它的名字.</p>
</div>
<div class="section" id="id2">
<h2>临时文件<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>如果你的应用需要用一临时文件来存储数据, 但不想和其他程序共享数据的话, 创建文件的最好方式是使用TemporaryFile()函数. 它在任意一个可能的平台上创建文件，并且能够随时断开链接. 这让其他程序不可能找到或访问这个文件,因为在文件系统表中没有它的引用.这个由TemporaryFile()创建的文件在关闭的时候自动删除.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">tempfile</span>

<span class="k">print</span> <span class="s">&#39;Building a file name yourself:&#39;</span>
<span class="n">filename</span> <span class="o">=</span> <span class="s">&#39;/tmp/guess_my_name.</span><span class="si">%s</span><span class="s">.txt&#39;</span> <span class="o">%</span> <span class="n">os</span><span class="o">.</span><span class="n">getpid</span><span class="p">()</span>
<span class="n">temp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s">&#39;w+b&#39;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;temp:&#39;</span><span class="p">,</span> <span class="n">temp</span>
    <span class="k">print</span> <span class="s">&#39;temp.name:&#39;</span><span class="p">,</span> <span class="n">temp</span><span class="o">.</span><span class="n">name</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">temp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="c"># Clean up the temporary file yourself</span>
    <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>

<span class="k">print</span>
<span class="k">print</span> <span class="s">&#39;TemporaryFile:&#39;</span>
<span class="n">temp</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">TemporaryFile</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;temp:&#39;</span><span class="p">,</span> <span class="n">temp</span>
    <span class="k">print</span> <span class="s">&#39;temp.name:&#39;</span><span class="p">,</span> <span class="n">temp</span><span class="o">.</span><span class="n">name</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="c"># Automatically cleans up the file</span>
    <span class="n">temp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>这个例子说明了使用一个普通模式作为名字的文件和使用TemporaryFile()创建的文件的区别. 注意: TemporaryFile()返回的文件不含有名字.</p>
<div class="highlight-python"><pre>$ python tempfile_TemporaryFile.py
Building a file name yourself:
temp: &lt;open file '/tmp/guess_my_name.7297.txt', mode 'w+b' at 0x5c338&gt;
temp.name: /tmp/guess_my_name.7297.txt

TemporaryFile:
temp: &lt;open file '&lt;fdopen&gt;', mode 'w+b' at 0x5c410&gt;
temp.name: &lt;fdopen&gt;</pre>
</div>
<p>默认情况下, 文件以模式&#8217;w+b&#8217;方式被创建, 所以在所有平台上都是一致的, 你的程序都能写入和读取它.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">tempfile</span>

<span class="n">temp</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">TemporaryFile</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">temp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&#39;Some data&#39;</span><span class="p">)</span>
    <span class="n">temp</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>

    <span class="k">print</span> <span class="n">temp</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">temp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>在写入之后, 你需使用seek()将当前文件指针指向之前的位置以便能够读取刚才的写入的数据.</p>
<div class="highlight-python"><pre>$ python tempfile_TemporaryFile_binary.py
Some data</pre>
</div>
<p>如果你想要的是文本模式的临时文件, 可以传递mode=&#8217;w+t&#8217;:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">tempfile</span>

<span class="n">f</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">TemporaryFile</span><span class="p">(</span><span class="n">mode</span><span class="o">=</span><span class="s">&#39;w+t&#39;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">writelines</span><span class="p">([</span><span class="s">&#39;first</span><span class="se">\n</span><span class="s">&#39;</span><span class="p">,</span> <span class="s">&#39;second</span><span class="se">\n</span><span class="s">&#39;</span><span class="p">])</span>
    <span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mf">0</span><span class="p">)</span>

    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="k">print</span> <span class="n">line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>这个文件把数据看成是文本字符串:</p>
<div class="highlight-python"><pre>$ python tempfile_TemporaryFile_text.py
first
second</pre>
</div>
</div>
<div class="section" id="id3">
<h2>命名临时文件<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
<p>在一些情况下, 也需要命名临时文件. 如果你的程序跨越多个进程, 或者甚至是主机, 命名文件是一种最简单的在程序各部分间传递数据的方式. NamedTemporaryFile()函数创建了一个有名字的, 即可以按名访问的文件.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">tempfile</span>

<span class="n">temp</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">NamedTemporaryFile</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;temp:&#39;</span><span class="p">,</span> <span class="n">temp</span>
    <span class="k">print</span> <span class="s">&#39;temp.name:&#39;</span><span class="p">,</span> <span class="n">temp</span><span class="o">.</span><span class="n">name</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="c"># Automatically cleans up the file</span>
    <span class="n">temp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="k">print</span> <span class="s">&#39;Exists after close:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">temp</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
</pre></div>
</div>
<p>即使文件被命名了, 他仍然可以在处理结束后删除.</p>
<div class="highlight-python"><pre>$ python tempfile_NamedTemporaryFile.py
temp: &lt;open file '&lt;fdopen&gt;', mode 'w+b' at 0x5c338&gt;
temp.name: /var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmplBKZMv
Exists after close: False</pre>
</div>
</div>
<div class="section" id="mkdtemp">
<h2>mkdtemp<a class="headerlink" href="#mkdtemp" title="Permalink to this headline">¶</a></h2>
<p>如果你需要多个临时文件, 可以创建一个临时目录然后把所有文件放在这个目录中. 使用mkdtemp()函数来创建一个临时目录.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">tempfile</span>

<span class="n">directory_name</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">mkdtemp</span><span class="p">()</span>
<span class="k">print</span> <span class="n">directory_name</span>
<span class="c"># Clean up the directory yourself</span>
<span class="n">os</span><span class="o">.</span><span class="n">removedirs</span><span class="p">(</span><span class="n">directory_name</span><span class="p">)</span>
</pre></div>
</div>
<p>由于目录不是&#8221;opened&#8221;, 你需要手动将它删除.</p>
<div class="highlight-python"><pre>$ python tempfile_mkdtemp.py
/var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-/tmp0OsHPg</pre>
</div>
</div>
<div class="section" id="id4">
<h2>预测文件名<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h2>
<p>为了便于调试, 需要将原始临时文件的一些信息保留. 当然这样明显地比匿名临时文件不安全很多, 包括名字中的一部分信息能够让你检测这个文件是否正在被你的程序使用. 到目前为止描述的所有函数需要3个参数来在一定程度上控制你的文件名. 命名规则如下:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nb">dir</span> <span class="o">+</span> <span class="n">prefix</span> <span class="o">+</span> <span class="n">random</span> <span class="o">+</span> <span class="n">suffix</span>
</pre></div>
</div>
<p>除了random之外的所有参数值都被传递给TemporaryFile(), NamedTemporaryFile(), 和 mkdtemp(). 例如:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">tempfile</span>

<span class="n">temp</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">NamedTemporaryFile</span><span class="p">(</span><span class="n">suffix</span><span class="o">=</span><span class="s">&#39;_suffix&#39;</span><span class="p">,</span>
                                   <span class="n">prefix</span><span class="o">=</span><span class="s">&#39;prefix_&#39;</span><span class="p">,</span>
                                   <span class="nb">dir</span><span class="o">=</span><span class="s">&#39;/tmp&#39;</span><span class="p">,</span>
                                   <span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;temp:&#39;</span><span class="p">,</span> <span class="n">temp</span>
    <span class="k">print</span> <span class="s">&#39;temp.name:&#39;</span><span class="p">,</span> <span class="n">temp</span><span class="o">.</span><span class="n">name</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">temp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>prefix 和suffix参数再联合一个随机字符串生成一个文件名, dir参数指定新文件所在的位置.</p>
<div class="highlight-python"><pre>$ python tempfile_NamedTemporaryFile_args.py
temp: &lt;open file '&lt;fdopen&gt;', mode 'w+b' at 0x5c338&gt;
temp.name: /tmp/prefix_zy-7H3_suffix</pre>
</div>
</div>
<div class="section" id="id5">
<h2>临时文件的位置<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h2>
<p>如果你没有使用dir参数来指定一个目标目录, 那么, 临时文件所在的真实路径会根据你平台和设置来确定. tempfile模块包含2个用于查询运行时间相关设置的函数:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">tempfile</span>

<span class="k">print</span> <span class="s">&#39;gettempdir():&#39;</span><span class="p">,</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">gettempdir</span><span class="p">()</span>
<span class="k">print</span> <span class="s">&#39;gettempprefix():&#39;</span><span class="p">,</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">gettempprefix</span><span class="p">()</span>
</pre></div>
</div>
<p>gettempdir()返回放所有临时文件的默认目录. gettempprefix()返回新文件和目录名字的字符串前缀.</p>
<div class="highlight-python"><pre>$ python tempfile_settings.py
gettempdir(): /var/folders/9R/9R1t+tR02Raxzk+F71Q50U+++Uw/-Tmp-
gettempprefix(): tmp</pre>
</div>
<p>gettempdir() 返回值的确定是基于一个直接查找算法, 它从一个位置列表中找到第一个可以创建文件的目录. 库文档中说明:</p>
<p>Python查找一个标准目录列表, 将第一个用户有权限在其中创建文件的目录来设置tempdir . 这个列表是:</p>
<ol class="arabic">
<li><p class="first">环境变量TMPDIR中的目录名.</p>
</li>
<li><p class="first">环境变量TEMP中的目录.</p>
</li>
<li><p class="first">环境变量TMP中的目录.</p>
</li>
<li><p class="first">平台指定的位置:</p>
<blockquote>
<ul class="simple">
<li>在RiscOS上, 由Wimp$ScrapDir指定目录名字.</li>
<li>在Windows上, 以C:$backslash$TEMP, C:$backslash$TMP, $backslash$TEMP, 和 $backslash$TMP按序查找目录.</li>
<li>在其他平台上, 以/tmp, /var/tmp, 和/usr/tmp按序查找目录.</li>
</ul>
</blockquote>
</li>
<li><p class="first">最后一个是当前工作目录.</p>
</li>
</ol>
<p>如果你的程序需要一个在全局位置下存放所有的临时文件, 你需要明确设置这个位置但又不想通过环境变量来设置, 这样的话, 你可以直接设置tempfile.tempdir来指定.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">tempfile</span>

<span class="n">tempfile</span><span class="o">.</span><span class="n">tempdir</span> <span class="o">=</span> <span class="s">&#39;/I/changed/this/path&#39;</span>
<span class="k">print</span> <span class="s">&#39;gettempdir():&#39;</span><span class="p">,</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">gettempdir</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-python"><pre>$ python tempfile_tempdir.py
gettempdir(): /I/changed/this/path</pre>
</div>
</div>
<div class="section" id="id6">
<h2>参考<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li><a class="reference external" href="http://www.doughellmann.com/projects/PyMOTW/">Python Module of the Week Home</a></li>
<li><a class="reference external" href="http://www.doughellmann.com/downloads/PyMOTW-1.40.tar.gz">Download Sample Code</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="sched.html" title="PyMOTW: sched"
             >next</a> |</li>
        <li class="right" >
          <a href="asyncore.html" title="PyMOTW: asyncore"
             >previous</a> |</li>
        <li><a href="../index.html">PyMOTW Document v1.6 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; <a href="../copyright.html">Copyright</a> 2009, vbarter &amp; liz.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.3.
    </div>
  </body>
</html>